﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Workbench.Models
{
    [DebuggerDisplay("Name={Name}, Children={Children.Count}, Parent={ParentPOSType.Name}")]
    public class POSTypeModel : PersistableModel, IEquatable<POSTypeModel>
    {
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; RaisePropertyChanged(); }
        }

        public long ParentPOSTypeId;

        private POSTypeModel parentPOSType;
        public POSTypeModel ParentPOSType
        {
            get { return parentPOSType; }
            set { parentPOSType = value; RaisePropertyChanged(); }
        }

        private long count;
        public long Count
        {
            get { return count; }
            set { count = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<POSTypeModel> children = new ObservableCollection<POSTypeModel>();
        public ObservableCollection<POSTypeModel> Children
        {
            get { return children; } 
        }

        public bool Equals(POSTypeModel other)
        {
            if (other == null) return false;
            return RowId == other.RowId;
        }

        public override int GetHashCode()
        {
            return RowId.GetHashCode();
        }

        private class _EqualsByPath : IEqualityComparer<POSTypeModel>
        {
            private string GetPath(POSTypeModel model)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(model.name);
                while(model.parentPOSType != null)
                {
                    model = model.parentPOSType;
                    sb.Append(model.name);
                }
                return sb.ToString();
            }

            public bool Equals(POSTypeModel x, POSTypeModel y)
            {
 	            return string.Compare(GetPath(x), GetPath(y)) == 0;
            }

            public int GetHashCode(POSTypeModel obj)
            {
                int result = -1;
                if (obj != null)
                {
                    if (obj.name != null)
                    {
                        result ^= obj.name.GetHashCode();
                    }
                }
                return result;
            }
        }
        public static IEqualityComparer<POSTypeModel> EqualsByPath = new _EqualsByPath();
    }
}
